<template>
  <el-dialog :visible.sync="certDialog" title="证书信息" class="cert-dialog">
    <el-form
      label-width="120px"
      label-position="left"
      size="mini"
      :rules="certSelectionFormRule"
      :model="certSelection"
    >
      <el-row :gutter="2">
        <el-col :span="8" :offset="2">
          <el-form-item label="人员类型" prop="parentId" required>
            <el-select
              v-model="certSelection.parentId"
              @change="onCertDataTypeChange"
              placeholder="请选择人员类型"
              style="width: 100%"
            >
              <el-option
                v-for="types in certDataType"
                :key="`cert-datatype-${types.type_id}`"
                :value="types.type_id"
                :label="types.type_name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" :push="2" :pull="2">
          <el-form-item 
            label="资格证专业" 
            :prop="certDataSubTypeFromType === 2 ? 'title' : 'type_id'"
            required
          >
            <el-input
              v-if="certDataSubTypeFromType === 2"
              v-model="certSelection.title"
              placeholder="请输入资格证专业"
            ></el-input>
            <el-select
              v-else
              v-model="certSelection.type_id"
              placeholder="请选择资格证专业"
              style="width: 100%"
            >
              <el-option
                v-for="types in certDataSubType"
                :key="`cert-datasubtype-${types.type_id}`"
                :value="types.type_id"
                :label="types.type_name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18" :offset="2">
          <el-form-item label="证书编号" required>
            <el-input v-model="certSelection.cert_num"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="发证日期" required>
            <el-date-picker
              v-model="certSelection.cert_effect"
              type="date"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="有效期至" required>
            <el-date-picker
              v-model="certSelection.cert_overdate"
              type="date"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18" :offset="2">
          <el-form-item label="目前所挂企业">
            <a-company-selector
              @select="onSelectEnterprise"
              @input="onInputEnterprise"
              :label="certSelection.company"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8" :offset="2">
          <el-form-item label="所挂开始时间">
            <el-date-picker
              v-model="certSelection.offce_startdate"
              type="date"
              @change="onOffceStartdateChanged"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="2">
          <el-form-item label="所挂到期时间">
            <el-date-picker
              v-model="certSelection.offce_enddate"
              type="date"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer">
      <el-button
        type="primary"
        icon="el-icon-folder-add"
        size="mini"
        @click="onSaveCert()"
      >
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import ACompanySelector from '@/components/ACompanySelector/index.vue';
import { CertApi } from '@/api';
import Cert from '@/api/modules/Cert';

export default {
  components: {
    ACompanySelector,
  },
  props: {
    data: {
      type: Object,
      default: function () {
        return null;
      },
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validateCertOffceDate = (rule, value, callback) => {
      if (!this.certSelection.company) {
        callback();
      } else {
        if (!value) {
          callback(new Error('请选择挂靠时间'));
        }
        callback();
      }
    };
    return {
      certDialog: this.visible,
      certSelection: this.data || {},
      certDataType: [],
      certDataSubTypeFromType: 1,
      certDataSubType: [],
      certSelectionFormRule: {
        parentId: [
          { required: true, message: '请选择人员类型', trigger: 'change' },
        ],
        type_id: [
          { required: true, message: '请选择资格证专业', trigger: 'change' },
        ],
        title: [
          { required: true, message: '请填写资格证专业', trigger: 'blur' },
        ],
        cert_num: [
          { required: true, message: '请填写证书编号', trigger: 'change' },
        ],
        cert_effect: [
          { required: true, message: '请选择发证日期', trigger: 'change' },
        ],
        cert_overdate: [
          { required: true, message: '请选择证件到期时间', trigger: 'change' },
        ],
        offce_startdate: [
          { validator: validateCertOffceDate, trigger: 'change' },
        ],
        offce_enddate: [
          { validator: validateCertOffceDate, trigger: 'change' },
        ],
      },
    };
  },
  watch: {
    data: function () {
      this.certSelection = this.data;
    },
    visible: function () {
      this.showAddCertDialog();
      this.certDialog = this.visible;
    },
    certDialog: function () {
      this.$emit('update:visible', this.certDialog);
    },
    certSelection: {
      deep: true,
      immediate: true,
      handler: function () {
        this.$forceUpdate();
      },
    },
  },
  methods: {
    async fetchCertCategories(parentId) {
      const response = await CertApi.getDataType(parentId);
      if (!parentId) {
        this.certDataType = response.result.list;
      } else {
        this.certDataSubType = response.result.list;
      }
    },
    showAddCertDialog() {
      this.certSelection = this.data
        ? _.clone(this.data)
        : {
            type_id: '',
            title: '',  // 添加title字段初始化
            parentId: '', // 添加parentId字段初始化
          };
      // 处理非法数据
      this.dealIllegalData();

      this.certDialog = true;
      this.certDataType = [];
      this.certDataSubType = [];
      this.fetchCertCategories();
      if (this.certSelection.parentId) {
        this.fetchCertCategories(this.certSelection.parentId);
      }
    },
    dealIllegalData() {
      // 处理所挂开始时间
      if (this.certSelection.offce_startdate) {
        // 排除无效日期字符串，转换为Date对象
        const isInvalid = this.certSelection.offce_startdate === '0000-00-00 00:00:00' || this.certSelection.offce_startdate === '0000-00-00';
        this.certSelection.offce_startdate = isInvalid
          ? null // 无效日期设为null（避免显示错误）
          : (this.certSelection.offce_startdate instanceof Date
              ? this.certSelection.offce_startdate
              : new Date(this.certSelection.offce_startdate) // 字符串转Date
          );
      }

      // 处理所挂到期时间（同上）
      if (this.certSelection.offce_enddate) {
        const isInvalid = this.certSelection.offce_enddate === '0000-00-00 00:00:00' || this.certSelection.offce_enddate === '0000-00-00';
        this.certSelection.offce_enddate = isInvalid
          ? null
          : (this.certSelection.offce_enddate instanceof Date
              ? this.certSelection.offce_enddate
              : new Date(this.certSelection.offce_enddate)
          );
      }
    },
    onSelectEnterprise({ company_id, company_name }) {
      this.certSelection.company_id = company_id;
      this.certSelection.company = company_name;
    },
    onInputEnterprise(company_name) {
      this.certSelection.company_id = null;
      this.certSelection.company = company_name;
    },
    async onCertDataTypeChange(value) {
      // 更新父类型ID
      this.certSelection.parentId = value;
      
      // 获取子类型列表
      await this.fetchCertCategories(value);
      
      // 判断是否为手动录入模式
      const isManualInput = this.certDataSubType.length === 1 && 
        this.certDataSubType[0].type_name === '*手动录入*';
      
      if (isManualInput) {
        // 手动录入模式
        this.certDataSubTypeFromType = 2;
        // 赋值type_id方便后端关联parent
        this.$set(this.certSelection, 'type_id', this.certDataSubType[0].type_id);
        this.$set(this.certSelection, 'title', ''); // 初始化title为空字符串
      } else {
        // 下拉选择模式
        this.certDataSubTypeFromType = 1;
        this.$set(this.certSelection, 'type_id', '');
        this.$set(this.certSelection, 'title', null);
      }
    },
    onOffceStartdateChanged(value) {
      console.log(value);
    },
    async onSaveCert() {
      if (this.certSelection.data_id) {
        await this.onEditCert();
      } else {
        await this.onAddCert();
      }

      this.$emit('save-cert-success');
    },
    async onAddCert() {
      const client_id = this.$route.query.id;
      if (!client_id) {
        this.$message.warning('请先保存用户信息');
      } else {
        const cert = _.clone(this.certSelection);
        cert.client_id = client_id;
        await Cert.addCert(client_id, cert, 1);
        this.$message.success('操作成功');
        this.certDialog = false;
      }
    },
    async onEditCert() {
      try {
        const cert = _.clone(this.certSelection);

        console.log(cert);
        await Cert.updateCert(this.$route.query.id, cert);

        this.$message.success('操作成功');
        this.certDialog = false;
      } catch (e) {
        this.$message.error('接口错误：' + JSON.stringify(e));
      }
    },
  },
};
</script>
